<template>
  <div class="login">
   <van-nav-bar title="登录"  />
   <van-form validate-first>
   <van-cell-group>
  <van-field  label="手机号" required :error-message='mobile_message' :rules="[{pattern:/^1[3456789]\d{9}$/, message: '输入正确手机号'}]" placeholder="请输入手机号" v-model.trim="mobile" />
  </van-cell-group>
  <van-cell-group>
  <van-field  label="密码" required :error-message="code_message" type="password" placeholder="请输入密码" v-model.trim='code'/>
  </van-cell-group>
  <div class="warp-div">
 <van-button class="btn" type="primary" @click='login'>登录</van-button>
  </div>
   </van-form>
  </div>
</template>

<script>
import { userLogin } from '@/api/user'
export default {
  name: 'login-page',
  data () {
    return {
      mobile: '',
      code: '',
      // 验证提示信息
      mobile_message: '',
      code_message: ''
    }
  },
  methods: {
    // 自定义的校验函数
    check () {
      // 如果内容是空的刷 就将提示信息 传递给你的错误提示
      this.mobile_message = this.moblie === '' ? '你的手机号要写' : ''
      this.code_message = this.code === '' ? '你的验证码要写' : ''
      if (this.moblie === '') {
        return false
      }
      if (this.code === '') {
        return false
      }
      return true
    },
    // 登录操作
    async login () {
      if (!this.check()) {
        return
      }
      // 提示登陆中
      this.$toast.loading({
        duration: 0, // 永远不会关闭
        mask: true,
        message: '登陆中....'
      });
      console.log(this.mobile, this.code);
      try {
        const result = await userLogin(this.mobile, this.code)
        // 登录成功后,保存token到vuex中
        this.$store.commit('mSetTokenInfo', result.data.data)
        this.$toast.success('登陆成功')
        // 跳转到layout页面
        const backto = this.$route.query.backto || '/'
        this.$router.push(backto)
      } catch (error) {
        console.log(error);
        this.$toast.fail('登陆失败')
      }
    }
  }
}
</script>

<style lang='less' scoped>
.login{
.warp-div{
  padding: 20px;
  .btn{
    width:100%;
    background-color: #6db4fd;
    color:#fff
  }
}
}

</style>
